package com.qsmx.store.app.http;

import com.qsmx.store.app.util.MD5Util;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.WeakHashMap;

/**
 * 文 件 名:
 * 描    述:
 * 创 建 人:  Xian
 * 创建时间:  2016/7/5 0005 下午 3:28
 */
public class BaseRequestWrapper {
    private static final String REQUEST_NAME = "requestName";
    private static final String PARAMS = "params";
    private static final String SIGN = "sign";
    private static final String TIMESTAMP = "timestamp";
    private static final String SECRET = "test";
    private WeakHashMap<String, Object> map;

    /**
     * 基础请求封装器
     */
    public WeakHashMap<String, Object> BaseRequestWrapper(String requestName, JSONObject paramMap) {
        map = new WeakHashMap<String, Object>();

        String paramStr = paramMap.toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(new Date());
        String signStr = getSignStr(requestName, paramStr, timestamp);

        map.put(REQUEST_NAME, requestName);
        map.put(PARAMS, paramStr);
        map.put(SIGN, signStr);
        map.put(TIMESTAMP, timestamp);
        return map;
    }

    public static String getSignStr(String requestName, String paramStr, String timestamp) {
        List<String> paramsList = new ArrayList<>();
        paramsList.add(REQUEST_NAME + "=" + requestName);
        paramsList.add(PARAMS + "=" + paramStr);

        paramsList.add(TIMESTAMP + "=" + timestamp);

        String signStr = "";
        Collections.sort(paramsList);
        for (String param : paramsList) {
            signStr += param;
        }
        signStr = signStr.replace("=", "");
        signStr = SECRET + signStr + SECRET;
        signStr = MD5Util.MD5(signStr).toLowerCase();
        return signStr;
    }
}
